package com.example.apptest.fragment;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.app_test.R;
import com.example.apptest.events.EventNotifyChange;
import com.example.apptest.events.EventScanResult;
import com.example.apptest.utils.BLEHelper;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class ListFragment extends Fragment {

    private ImageView notifyView;
    private ListView lv;
    private Integer[] imgId = {R.drawable.s_1, R.drawable.s_2, R.drawable.s_3, R.drawable.s_4};
    private String[]  txtArray = {"香蕉","桔子","苹果","桃子"};

    private List<Integer> imgIdList = new ArrayList<>();
    private List<String> txtList = new ArrayList<>();
    private List<BluetoothDevice> devList = new ArrayList<>();

    private BLEHelper bleHelper;

    BaseAdapter adapter = new BaseAdapter() {
        @Override
        public int getCount() {
            return imgIdList.size();
        }

        @Override
        public Object getItem(int position) {
            return imgId[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if(convertView == null) {
                convertView = View.inflate(getActivity(), R.layout.list_item, null);
                ViewHolder viewHolder = new ViewHolder();
                viewHolder.image = convertView.findViewById(R.id.item_img);
                viewHolder.text = convertView.findViewById(R.id.item_tv);
                convertView.setTag(viewHolder);
                convertView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        bleHelper.connectToDevice(devList.get(position));
                    }
                });
            }
            ViewHolder viewHolder = (ViewHolder)convertView.getTag();
            if(imgIdList.size() > position) {
                viewHolder.image.setImageResource(imgIdList.get(position));
                viewHolder.text.setText(txtList.get(position));
            }
            return convertView;
        }
    };

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(v.getId() == R.id.btn_spin) {
                bleHelper.sendData(new byte[]{0x01});
            } else if(v.getId() == R.id.btn_move) {
                bleHelper.sendData(new byte[]{0x02});
            } else if(v.getId() == R.id.btn_scan) {
                bleHelper.ScanDevices();
            } else if(v.getId() == R.id.btn_notify) {
                bleHelper.notifyToggle();
            }
        }
    };

    static private ListFragment instance = null;
    private ListFragment() {}
    static public ListFragment getInstance() {
        if(instance == null) {
            instance = new ListFragment();
        }
        return instance;
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        instance = null;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_list, null);
        lv = view.findViewById(R.id.lv);
        lv.setAdapter(adapter);

        view.findViewById(R.id.btn_spin).setOnClickListener(onClickListener);
        view.findViewById(R.id.btn_move).setOnClickListener(onClickListener);
        view.findViewById(R.id.btn_scan).setOnClickListener(onClickListener);
        notifyView = view.findViewById(R.id.btn_notify);
        notifyView.setOnClickListener(onClickListener);

        BluetoothManager manager = (BluetoothManager)getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
        bleHelper = BLEHelper.getInstance();

        EventBus.getDefault().register(this);
        return view;
    }
    class ViewHolder {
        ImageView image;
        TextView text;
    }

    @SuppressLint("MissingPermission")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventScanResult(EventScanResult scanResult){
        String name = scanResult.device.getName();
        if(scanResult.device.getAddress() != null) {
            if(name != null) {
                if(!txtList.contains(name)) {
                    imgIdList.add(imgId[0]);
                    txtList.add(name);
                    devList.add(scanResult.device);
                    adapter.notifyDataSetChanged();
                }
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventNotifyChange(EventNotifyChange event) {
        if(notifyView != null) {
            if(event.notifyNo)
                notifyView.setImageResource(R.color.green);
            else
                notifyView.setImageResource(R.color.red);
        }
    }
}